< previous page page_231 next page >

Page 231
One way to use the Exit Sub statement is in the beginning of the procedure in a routine that checks parameters for proper values. If any of the parameters passed to procedure are the wrong type or have values that could cause a problem for the procedure, use Exit Sub to terminate the procedure before the error occurs. Using the statement this way is a type of data validation. The following code modifies the previous area calculation code to perform this check:
Sub CalcRectangle(nWidth as Integer, nHeight as Integer, nArea as Integer, _
                  nPerimeter as Integer)
If nWidth <= 0 Or nHeight <= 0 Then
     Exit Sub
   End If
   nArea = nWidth * nHeight
   nPerimeter = 2 * (nWidth + nHeight)
End Sub
Working with Functions
Functions are similar to procedures, with one key difference: they return a value. This value can be assigned to a variable or used in expressions. Visual Basic offers a number of built-in functions that you can use, such as Abs, which returns the absolute value of a number, or Left, which returns a specified number of characters from the left end of a string. You can build your own functions as well.
To build a function, you have the same two choices you had in building a procedurestarting from scratch or using the Add Procedure dialog box. To start from scratch, select the place in the Code window where you want the function to start and then enter the keyword Function followed by the name of the function. The naming conventions for functions are the same as those for procedures. To use the Add Procedure dialog box, just select the Function Type option button in the dialog box. Either method creates the shell of a function just as it does for a procedure. An example of this shell is shown in the following lines of code:
Public Function NumAverage()

End Function
Although the first line is an acceptable function declaration, most of the time you will define the type of value that will be returned by the function. You define this function type like you define variable types in a Dim statementby using the As keyword followed by the variable type. This function type declaration follows the parentheses that enclose the parameter declaration. In addition, you will typically declare the parameters that are passed to the function in the declaration statement. A more complete declaration statement is shown in the following line:
Public Function NumAverage(inpt1 As Single, inpt2 As Single) As Single
The other key difference between building a function and a procedure is that you assign a value to the function name somewhere within the code of the function. This value must be of the same type as specified in the function declaration. This is shown in the second line of the following code:

 
< previous page page_231 next page >